package com.framework.modules.oss.controller;

import java.util.*;

import com.framework.common.oss.CloudUploadResponse;
import com.framework.common.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.framework.common.exception.RRException;
import com.framework.common.validator.ValidatorUtils;
import com.framework.common.validator.group.AliyunOssGroup;
import com.framework.common.validator.group.QcloudQssGroup;
import com.framework.common.validator.group.QiniuOssGroup;
import com.framework.common.oss.CloudStorageConfig;
import com.framework.common.oss.OSSFactory;
import com.framework.modules.sys.entity.SysOssEntity;
import com.framework.modules.sys.service.SysOssService;
import com.framework.modules.sys.service.SysConfigService;
import com.google.gson.Gson;

/**
 * 文件上传
 */
@RestController
@RequestMapping("sys/oss")
@Api(tags = "OSS服务")
public class SysOssController {
	@Autowired
	private SysOssService sysOssService;
	@Autowired
	private SysConfigService sysConfigService;

	/**
	 * 列表F
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:oss:all")
	@ApiOperation("OSS列表")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = sysOssService.queryPage(params);
		return R.ok().put("page", page);
	}

	/**
	 * 云存储配置信息
	 */
	@RequestMapping("/config")
	@RequiresPermissions("sys:oss:all")
	@ApiOperation("获取配置")
	public R config() {
		CloudStorageConfig config = sysConfigService.getConfigObject(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY, CloudStorageConfig.class);

		return R.ok().put("config", config);
	}

	/**
	 * 保存云存储配置信息
	 */
	@RequestMapping("/saveConfig")
	@RequiresPermissions("sys:oss:all")
	@ApiOperation("保存配置")
	public R saveConfig(@RequestBody CloudStorageConfig config) {
		// 校验类型
		ValidatorUtils.validateEntity(config);

		if (config.getType() == Constant.CloudService.QINIU.getValue()) {
			// 校验七牛数据
			ValidatorUtils.validateEntity(config, QiniuOssGroup.class);
		} else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
			// 校验阿里云数据
			ValidatorUtils.validateEntity(config, AliyunOssGroup.class);
		} else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
			// 校验腾讯云数据
			ValidatorUtils.validateEntity(config, QcloudQssGroup.class);
		}

		sysConfigService.updateValueByKey(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY, new Gson().toJson(config));

		return R.ok();
	}

	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	@RequiresPermissions("sys:oss:all")
	@ApiOperation("上传文件")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {

		String type = HttpContextUtils.getHttpServletRequest().getParameter("type");

		if(StringUtils.isBlank(type)) {
			return R.error("合法目录为空,必须指定一个合法的存储目录");
		}
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		Map<String, String> maps = QuickHelper.getClassFiledsKeyValueMap(OSSFactory.DirectoryConfig);
		String[] values = QuickHelper.getMapValueStringArray(maps);

		if (!maps.containsValue(type)) {
			return R.error(-1, String.format("您的文件目录不是允许的范围( %s )，请重新输入", StringUtils.join(values," , ")));
		}

		//文件存储路径
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String path = QuickHelper.createCloudStorageFileName(suffix, type);
		CloudUploadResponse res = OSSFactory.create().upload(file.getBytes(), path);

		String url = res.getUrl();

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setPath(res.getPath());
		ossEntity.setExt(res.getExt());
		ossEntity.setFilesize(res.getFilesize());
		ossEntity.setSource(res.getSource());
		ossEntity.setCreateDate(new Date());
		sysOssService.insert(ossEntity);

		return R.ok().put("url", url);
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	@ApiOperation("删除配置")
	public R delete(@RequestBody Long[] ids) {
		sysOssService.deleteBatchIds(Arrays.asList(ids));

		return R.ok();
	}

}
